﻿var User = require("./User");
var gameDao = require("./../dao/gameDao");
var redis_dao = require("./../dao/redis_dao");
var arithmetic = require("./arithmetic")
var sever = require("./sever");
var schedule = require("node-schedule");
var gameConfig = require("./../config/gameConfig");
var urlencode = require('urlencode');
var fs = require('fs');
var log = require("./../../util/loginfo").getInstand;

// var redis = require("redis");
// var client = redis.createClient(6379,"127.0.0.1");

var laba = require("./../../util/laba");
var redis_send_and_listen = require("./../../util/redis_send_and_listen");
//读取文件包


var GameInfo = function () {

    var _gameinfo = "";

    var Game = function () {

        //初始化算法，使用第X种
        this.initAlgorithm = function (idx) {
            log.info('####init Algorithm!####');
            log.info('use [' + idx + '] Algorithm!');
            this.A = new arithmetic(idx);
        };

        this.serverId = gameConfig.serverId;

        //初始化游戏
        this.init = function () {
            log.info('####init game!####');

            //初始化算法
            this.initAlgorithm(0);
            //初始化用户列表
            this.userList = {};
            //在线人数为0
            this.onlinePlayerCount = 0;
            //统计
            this.winTotal = 0;
            this.lotteryCount = 0;
            this.hourWinTotal = 0;
            this.hourlotteryCount = 0;

            this.bet_list = {};
            //初始化清除数组
            redis_dao.init_bet_list();
            this.remaintimes = 0;   //初始化剩余时间

            this.game_record_list = [];   //游戏记录

            this.bet_pai_hang_list = [];  //玩家下注排行榜
            this.shen_suan_zi = {};  //神算子

            this.score_changeLogList = [];
            this.lotteryLogList = [];
            this.lineOutList = [];
            //维护模式
            this.maintain = false;
            this.times_id = 0;     //当前的局号
            this.game_type = 3;    //游戏状态   0 默认   1开始下注  2 开奖   3结束  4开始抢庄
            this.game_second = 0; //秒数

            this.sever = new sever();
            //查日志
            gameDao.selectGameLog((result) => {
                if (result == 0) {
                    this.times_id = 10000001;
                } else {
                    this.times_id = result[0].id + 1;
                }
                log.info("初始局号: " + this.times_id);
            });
            var rule = new schedule.RecurrenceRule();
            var times = [];
            for (var i = 0; i < 60; i++) {
                times.push(i);
            }
            rule.second = times;
            var self = this;
            schedule.scheduleJob(rule, function () {

                if (gameConfig.maintain) {
                    --gameConfig.maintainTime;
                    //log.info(gameConfig.maintainTime);;
                    if (!gameConfig.maintainTime) {
                        self.disconnectAllUser();
                    }
                }

                var nowDate = new Date();
                var minute = nowDate.getMinutes();
                var second = nowDate.getSeconds();

                // log.info(self.onlinePlayerCount)

                if (self.remaintimes > 0) {
                    self.remaintimes--;
                }

                self.game_second = second;
                if (self.game_type === 0) {    //有人就开局
                    log.info("开始下注  清除数组");
                    redis_dao.init_bet_list();
                    self.game_type = 1;
                    self.remaintimes = gameConfig.GAME_BET_TIME;
                    self._io.sockets.emit('BetStart', {
                        result: true,
                        type: 1,
                        times: gameConfig.GAME_BET_TIME
                    });

                }
                if (self.remaintimes <= 0 && self.game_type === 1) {
                    log.info("开奖");
                    //开奖
                    self.game_type = 2;
                    self.remaintimes = gameConfig.GAME_END_TIME;
                    self.open_win();
                }

                if (self.remaintimes <= 0 && self.game_type === 2) {
                    self.game_type = 3;
                    gameDao.selectGameLog((result) => {
                        self.times_id = result[0].id + 1;
                        log.info("开奖结束循环局号: " + self.times_id);
                    });
                }

                if (self.game_type === 3 && self.onlinePlayerCount > 0) {
                    log.info("开始新一轮");
                    self.game_type = 0;
                }


                if (second === 0) {
                    redis_send_and_listen.send_msg("OnlineUserMsg", {
                        server_id: gameConfig.serverId,
                        online_num: self.onlinePlayerCount
                    });
                    //log.info("推送在线人数");
                }
            });
        };

        this.lottery = function (_userId, _bet_dict) {
            //下注
            let bet_dict = _bet_dict;
            log.info("lottery bet_dict " + JSON.stringify(bet_dict));

            if (this.game_type !== 1) {		//不是下注时间
                log.info("不是下注时间");
                return {code: -1};
            }
            if (!_userId) {					//传输ID错误
                log.info("未传用户ID");
                return {code: -1};
            }
            if (!this.userList[_userId]) {	//未找到用户
                log.info("找不到用户");
                return {code: -1}
            }

            let nBetSum = 0;
            //检查下注字典
            if (typeof (bet_dict.bet_gold) != 'number' || !gameConfig.coinConfig[bet_dict.bet_gold]) {
                log.info("字段bet_gold数据异常");
                return {code: -1};
            }
            if (typeof (bet_dict.bet_res) != 'number' || bet_dict.bet_res >= gameConfig.GAME_COLOR_TYPE) {
                log.info("字段bet_res数据异常");
                return {code: -1};
            }
            nBetSum += gameConfig.coinConfig[bet_dict.bet_gold];

            //用户扣钱
            var lotteryResult = this.userList[_userId].lottery(nBetSum);
            if (!lotteryResult) {
                log.info(_userId + "分数不够");
                return {code: -2}
            }
            if (!this.bet_list[bet_dict.bet_res]) {
                this.bet_list[bet_dict.bet_res] = 0;
            }
            this.bet_list[bet_dict.bet_res] += nBetSum;
            log.info("bet list " + JSON.stringify(this.bet_list));

            var GamblingBalanceLevelBigWin = this.A.getGamblingBalanceLevelBigWin(); //获取库存 水位 大奖幸运值
            var nGamblingWaterLevelGold = GamblingBalanceLevelBigWin.nGamblingWaterLevelGold; //水位  抽水
            var addBalanceGold = parseInt(nBetSum * parseFloat(nGamblingWaterLevelGold / 100));    //进入库存的钱
            var addWinPool = nBetSum - addBalanceGold;                  //进入奖池的钱

            //增加库存和奖池
            if (!this.userList[_userId]._Robot) {
                this.A.addGamblingBalanceGold(addBalanceGold, addWinPool);
            }

            bet_dict.isRobot = this.userList[_userId]._Robot;
            bet_dict.bet_sum = nBetSum;
            bet_dict.userId = _userId;
            log.info("bet info " + JSON.stringify(bet_dict));

            //添加数据
            try {
                redis_dao.save_bet(bet_dict);
            } catch (e) {
                log.info("下注添加数据报错");
            }

            return {code: 2, bet_dict: bet_dict};

        };

        this.tt = 0;

        this.open_win = function () {
            log.info("开始开奖");
            if (this.game_type !== 2) {
                log.info("game_type不是2 不能开奖:" + this.game_type);
                return;
            }
            //开奖
            //获取下注数据
            redis_dao.get_bet_list().then(res => {

                var redis_dict = res;
                var GamblingBalanceLevelBigWin = this.A.getGamblingBalanceLevelBigWin(); //获取库存 水位 大奖幸运值
                //奖池
                var nGamblingWinPool = GamblingBalanceLevelBigWin.nGamblingWinPool;
                //库存
                var nGamblingBalanceGold = GamblingBalanceLevelBigWin.nGamblingBalanceGold;
                //抽水
                var nGamblingWaterLevelGold = GamblingBalanceLevelBigWin.nGamblingWaterLevelGold;

                var user_bet_list = [];
                for (var i in redis_dict) {
                    var betInfo = redis_dict[i];   //下注详情
                    let flag = false;
                    for (var j in user_bet_list) {
                        if (betInfo.userId == user_bet_list[j]["userId"] && betInfo.bet_res == user_bet_list[j]["bet_res"]) {
                            user_bet_list[j]["bet_gold"] += parseInt(betInfo.bet_gold);
                            user_bet_list[j]["bet_sum"] += parseInt(gameConfig.coinConfig[betInfo.bet_gold]);
                            flag = true;
                            break;
                        }
                    }
                    if (!flag) {
                        user_bet_list.push({
                            "userId": parseInt(betInfo.userId),
                            "bet_res": parseInt(betInfo.bet_res),
                            "bet_gold": parseInt(betInfo.bet_gold),
                            "bet_sum": parseInt(gameConfig.coinConfig[betInfo.bet_gold])
                        });
                    }
                }

                log.info("user bet list " + JSON.stringify(user_bet_list));
                // log.info("下注信息--------------------------------------")
                // log.info(redis_dict)

                let dictAnalyseResults = this.A.gameProcessor(redis_dict, nGamblingWinPool);//结果


                dictAnalyseResults["user_bet_list"] = user_bet_list; //下注详情

                // log.info(dictAnalyseResults)

                var user_robot_dict = dictAnalyseResults["user_robot_dict"];

                var winscore = 0;
                for (let i in dictAnalyseResults["win_user_list"]) {
                    var user_win = dictAnalyseResults["win_user_list"][i];
                    var is_robot = false;
                    for (let j in redis_dict) {
                        if (redis_dict[j].userId == i) {
                            is_robot = redis_dict[j].isRobot;
                            break;
                        }
                    }

                    if (!is_robot) {
                        winscore += user_win;
                    }
                    this.GameBalance(i, user_win);
                }

                // log.info("下注后-------------------",winscore);

                //减少奖池
                if (winscore > 0) {
                    this.A.subGamblingBalanceGold(0, winscore);
                }

                //制作结果
                var result = {
                    ResultCode: 1,
                    win: dictAnalyseResults["win"],
                    win_res: dictAnalyseResults["win_res"],
                };
                log.info("开奖结果:", result);

                var user_win_list = dictAnalyseResults["win_user_list"];

                //推消息
                for (let u in this.userList) {
                    var send_data = {
                        win: dictAnalyseResults["win"],
                        win_res: dictAnalyseResults["win_res"],
                    };
                    var user_win = 0;
                    if (user_win_list) {
                        if (user_win_list[u]) {
                            user_win = user_win_list[u];
                        }
                    }
                    send_data["user_win"] = user_win;
                    send_data["user_score"] = this.userList[u].getScore();

                    for (let i in user_bet_list) {
                        let betInfo = user_bet_list[i];
                        if (betInfo == null) {
                            continue;
                        }
                        if (betInfo.userId == u) {
                            send_data["user_bet"] += betInfo["bet_sum"];
                        }
                    }
                    this.userList[u]._socket.emit('OpenWinResult', send_data);
                }

                //1.写记录
                var user_bet_sum_list = dictAnalyseResults["user_bet_sum_list"];
                var CoinLog = [];
                for (let i in user_win_list) {
                    if (i <= 10000) {
                        continue;
                    }

                    let betlist_array = [];
                    for (let j in user_bet_list) {
                        let betInfo = user_bet_list[j];
                        let userId = betInfo["userId"];
                        if (parseInt(userId) == parseInt(i)) {
                            let info = {};
                            info[betInfo["bet_res"].toString()] = betInfo["bet_sum"],
                            betlist_array.push(info);
                        }
                    }
                    log.info("insert mark bet sum: ", user_bet_sum_list[i], " bet detail ", JSON.stringify(user_bet_list)," open win bet info ", JSON.stringify(betlist_array));

                    var logTemp = {
                        userId: parseInt(i),
                        useCoin: user_bet_sum_list[i],
                        winCoin: user_win_list[i],
                        tax: 0,
                        serverId: gameConfig.serverId,
                        gameId: gameConfig.gameId,
                        round_no: this.times_id,
                        bet_list: JSON.stringify(betlist_array),
                        result: JSON.stringify(dictAnalyseResults["win"])
                    };
                    CoinLog.push(logTemp);

                }
                if (CoinLog.length > 0) {
                    this._Csocket.emit("insertMark", CoinLog);
                    log.info("insert mark round no == " + this.times_id);
                }

                this.bet_list = {};
                //保存奖池
                this.saveGamblingBalanceGold();
                //存日志
                gameDao.saveGameLog(JSON.stringify(dictAnalyseResults));

                dictAnalyseResults["open_time"] = Number(new Date());

                this.game_record_list.push(dictAnalyseResults);
                if (this.game_record_list.length > 15) {
                    this.game_record_list.splice(0, 1);
                }

                //计算玩家排行榜
                var game_record_list_length = this.game_record_list.length;
                var user_bet_sum_all = {};
                var user_bet_true_all = {};

                var new_game_record_list = JSON.parse(JSON.stringify(this.game_record_list));
                new_game_record_list.reverse();

                var for_num = 0;
                if (new_game_record_list.length > 15) {
                    for_num = 15;
                } else if (game_record_list_length > 0 && game_record_list_length <= 15) {
                    for_num = game_record_list_length - 1;
                }

                for (let i = 0; i < for_num; i++) {
                    var i_user_bet_sum_list = new_game_record_list[i].user_bet_sum_list;
                    for (var i_us in i_user_bet_sum_list) {
                        if (!user_bet_sum_all[i_us]) {
                            user_bet_sum_all[i_us] = 0
                        }
                        user_bet_sum_all[i_us] += i_user_bet_sum_list[i_us]
                    }
                    var i_user_bet_true_list = new_game_record_list[i].user_bet_true_list;
                    for (var i_ub in i_user_bet_true_list) {
                        var u_b_t = i_user_bet_true_list[i_ub];
                        if (!user_bet_true_all[u_b_t]) {
                            user_bet_true_all[u_b_t] = 0
                        }
                        user_bet_true_all[u_b_t]++
                    }
                }
                var bet_sum_all_key_score = {};
                for (var ub in user_bet_sum_all) {
                    bet_sum_all_key_score[user_bet_sum_all[ub]] = ub
                }

                var bet_true_all_key_num = {};
                for (var ubt in user_bet_true_all) {
                    bet_true_all_key_num[user_bet_true_all[ubt]] = ubt
                }


                var pai_hang_list = [];
                for (let keys of Object.keys(bet_sum_all_key_score).sort(function (a, b) {
                    return parseInt(a) - parseInt(b)
                })) {
                    if (pai_hang_list.length < 101 && this.userList[bet_sum_all_key_score[keys]]) {
                        pai_hang_list.push({
                            user_id: bet_sum_all_key_score[keys],
                            bet_score: keys,
                            user_name: this.userList[bet_sum_all_key_score[keys]]._nickname,
                            user_url: this.userList[bet_sum_all_key_score[keys]]._headimgurl,
                            win_num: user_bet_true_all[bet_sum_all_key_score[keys]],
                            score: this.userList[bet_sum_all_key_score[keys]]._score,
                        })
                    }
                    // log.info(keys, bet_sum_all_key_score[keys]);
                }
                this.bet_pai_hang_list = pai_hang_list;


                // log.info("----------------------------------bet_true_all_key_num")
                // log.info(bet_true_all_key_num)
                var shen_suan = {};
                for (let keys of Object.keys(bet_true_all_key_num).sort(function (a, b) {
                    return parseInt(a) - parseInt(b)
                })) {
                    var ex_user_id = parseInt(bet_true_all_key_num[keys])
                    if (this.userList[ex_user_id]) {
                        if (isEmptyObject(shen_suan)) {
                            shen_suan = {
                                user_id: ex_user_id,
                                win_num: parseInt(keys),
                                user_name: this.userList[ex_user_id]._nickname,
                                user_url: this.userList[ex_user_id]._headimgurl,
                                score: this.userList[ex_user_id]._score,
                            }
                        } else if (parseInt(this.shen_suan_zi.win_num) == parseInt(keys) && parseInt(user_bet_sum_all[bet_true_all_key_num[keys]]) > parseInt(user_bet_sum_all[this.shen_suan_zi.user_id])) {
                            shen_suan = {
                                user_id: bet_true_all_key_num[keys],
                                win_num: keys,
                                user_name: this.userList[bet_true_all_key_num[keys]]._nickname,
                                user_url: this.userList[bet_true_all_key_num[keys]]._headimgurl,
                                score: this.userList[bet_true_all_key_num[keys]]._score,
                            }
                        }

                    }
                    // log.info(keys, bet_sum_all_key_score[keys]);
                }

                this.shen_suan_zi = shen_suan;
            }).catch(e => {
                log.err(e);
            });
        };


        this.setIo = function (_io, _Csocket) {
            this.sever.setIo(_io, _Csocket);
            this._io = _io;
            this._Csocket = _Csocket;
        };


        this.Setmaintain = function () {
            gameConfig.maintain = true;
        };

        this.isMaintain = function () {
            return gameConfig.maintain;
        };

        //判断是否是同一scoket连续登录，不允许
        this.isLoginAgain = function (socket) {
            if (socket.userId) {
                return this.userList[socket.userId].Islogin();
            } else {
                return false;
            }
        };

        //添加用户
        this.addUser = function (_userInfo, socket) {
            this.userList[_userInfo.userid] = new User(_userInfo, socket);
        };

        this.updateUser = function (userInfo) {
            log.info("update");
            if (!this.userList[userInfo._userId]) return;

            //已经断线
            if (this.userList[userInfo._userId]._isLeave) {
                var result = {ResultCode: 0, userId: userInfo._userId};
                this._Csocket.emit("userDisconnect", result);
                delete this.userList[userInfo._userId];
                return;
            }
            this.userList[userInfo._userId].update(userInfo);

            this.LoginGame(userInfo._userId, this.serverId);
            ++this.onlinePlayerCount;

            var self = this;
            var resultObj = {
                account: self.userList[userInfo._userId]._account,
                id: self.userList[userInfo._userId]._userId,
                nickname: self.userList[userInfo._userId]._nickname,
                score: self.userList[userInfo._userId]._score,
                headimgurl: self.userList[userInfo._userId]._headimgurl
            };
            result = {resultid: '1', msg: 'login lineserver succeed!', Obj: resultObj};
            this.userList[userInfo._userId]._socket.emit('loginGameResult', result);

        };

        //获得在线人数
        this.getOnlinePlayerCount = function () {
            return this.onlinePlayerCount;
        };

        //在线所有人
        this.getOnlinePlayer = function () {
            return this.userList;
        };

        this.score_changeLog = function () {
            var self = this;
            var saveListTemp = [];
            var ItemTemp;
            var max = 0;
            if (this.score_changeLogList.length > 200) {
                max = 200;
            } else {
                max = this.score_changeLogList.length;
            }
            for (var i = 0; i < max; i++) {
                if (this.score_changeLogList.length > 0) {
                    ItemTemp = this.score_changeLogList.shift();
                    saveListTemp.push(ItemTemp);
                }
            }
            if (saveListTemp.length > 0) {
                this._Csocket.emit("score_changeLog", saveListTemp);
                //gameDao.score_changeLog(saveListTemp);
            }
        };

        this.lotteryLog = function () {
            var self = this;
            var saveListLotteryLogTemp = [];
            var ItemTemp;
            var max = 0;
            if (this.lotteryLogList.length > 200) {
                max = 200;
            } else {
                max = this.lotteryLogList.length;
            }
            for (var i = 0; i < max; i++) {
                if (this.lotteryLogList.length > 0) {
                    ItemTemp = this.lotteryLogList.shift();
                    saveListLotteryLogTemp.push(ItemTemp);
                }
            }
            if (saveListLotteryLogTemp.length > 0) {
                gameDao.lotteryLog(saveListLotteryLogTemp);
            }
        };
        this.GameBalance = function (userItem, userWin) {
            log.info("GameBalance");
            log.info(userItem, userWin);
            //判断玩家是否在线
            if (this.userList[userItem]) {
                var youScore = this.userList[userItem].getScore();
                this.userList[userItem].winscore(userWin);
                var youNowScore = this.userList[userItem].getScore();
                //记录金钱变化量
                var userInfolog = {
                    userid: userItem,
                    score_before: youScore,
                    score_change: userWin,
                    score_current: youNowScore,
                    change_type: gameConfig.logflag,
                    isOnline: true
                };
                this.score_changeLogList.push(userInfolog);
            } else {
                this._Csocket.emit("GameBalance", {
                    signCode: gameConfig.LoginServeSign,
                    sendUserId: userItem,
                    sendCoin: userWin,
                    change_type: gameConfig.logflag
                })
            }
        };


        //删除用户
        this.deleteUser = function (_socket) {
            if (_socket.userId) {
                //存免费次数
                var info = {
                    userId: _socket.userId,
                    freeCount: this.userList[_socket.userId].getFreeCount(),
                    LotteryCount: this.userList[_socket.userId].getLotteryCount()
                };
                gameDao.saveFree(info, function (result) {
                    if (!result)
                        log.err("存免费次数:" + _userinfo.userId + "失败!")
                });
                this._Csocket.emit("lineOut", {
                    signCode: gameConfig.LoginServeSign,
                    state: 0,
                    gameId: gameConfig.gameId,
                    serverId: gameConfig.serverId,
                    userId: _socket.userId,
                    tableId: -1,
                    seatId: -1
                });
                this.sever.LogoutRoom(this.userList[_socket.userId], _socket);
                delete this.userList[_socket.userId];
                --this.onlinePlayerCount;
            }
        };

        //删除用户
        this.deleteUserById = function (_userId, msg) {
            if (_userId) {
                var socketItem = this.userList[_userId]._socket;
                result = {resultid: 0, msg: msg};
                socketItem.emit('loginGameResult', result);
                delete this.userList[_userId];
            }
        };

        //获得用户当前分数
        this.getUserscore = function (_userId) {
            if (_userId) {
                return this.userList[_userId]._score;
            }
        };

        //获得用户
        this.getUser = function (_userId) {
            if (_userId) {
                return this.userList[_userId];
            }
        };

        //用户是否在线
        this.IsPlayerOnline = function (_userId) {
            if (!_userId) {	//传输ID错误
                log.info("查询在线,参数错误");
                return -1;
            }
            if (this.userList[_userId]) {//未找到用户
                //log.info("查询在线,未找到" + _userId + "用户");
                return 1;
            } else {
                return 0;
            }
        };

        //获得用户当前分数
        this.getPlayerScore = function (_userId) {
            if (!_userId) {	//传输ID错误
                log.info("查询分数,参数错误");
                return -1;
            }
            if (this.userList[_userId]) {//未找到用户
                //log.info("查询在线,未找到" + _userId + "用户");
                return this.userList[_userId].getScore();
            } else {
                return -1;
            }
        };

        //GM加分
        this.addgold = function (_userId, score) {

            if (!_userId) {					//传输ID错误
                log.info("加分,未登录")
                return 0;
            }
            if (!this.userList[_userId]) {	//未找到用户
                log.info("加分,未登录")
                return 0
            } else {
                log.info(score)
                if (this.userList[_userId].addgold(score)) {
                    log.info(this.userList[_userId].getScore())
                    log.info("加分成功!")
                    var tablestring = "table" + this.userList[_userId].getTable();
                    this._io.sockets.in(tablestring).emit('addgoldResult', {
                        userId: _userId,
                        userSeatId: this.userList[_userId].getSeat(),
                        userScore: this.userList[_userId]._score
                    })
                    return 1;
                } else {
                    log.info("减分失败,大于用户分数!");
                    return 0;
                }
            }
        };

        //保存时间段输赢状况
        this.saveSocrePool = function () {
            //获得虚拟池
            var Virtualpool = this.A.getVirtualScorePool();
            //获得实际池
            var poollist = this.A.getScorePoolList();

            //var poollistLength = this.A.getScorePoolListLength();

            var poollistId = this.A.getScoreId();

            gameDao.Update_score_pool(poollist, Virtualpool, poollistId, function (Result) {
            })
        };

        //保存库存 奖池
        this.saveGamblingBalanceGold = function () {
            //获得库存奖池
            var dict = this.A.getGamblingBalanceGold();

            gameDao.Update_GamblingBalanceGold(dict.nGamblingBalanceGold, dict.nGamblingWinPool, function (Result) {
            })
        };


        //进入游戏
        this.LoginGame = function (_userId, gametype) {
            if (!this.userList[_userId]) return;
            //用户添加游戏ID
            //log.info(_userId)
            //log.info("用户进入游戏" + gametype);
            this.userList[_userId].loginGame(gametype);
        };


        //进入房间
        this.LoginRoom = function (_userId, roomid, _socket) {
            if (!this.userList[_userId]) return;


            if (!this.userList[_userId].getGameId()) {
                log.info("用户" + _userId + ",没有进入任何游戏,进入房间")
                return;
            }

            if (this.userList[_userId].getSeat() != -1) {
                log.info("用户" + _userId + "已经有座位");
                return;
            }

            this.userList[_userId].loginRoom(roomid);
            var LoginResult;
            var linemsg = this.getLineOutMsg(_userId);
            if (linemsg.Result) {
                log.info("断线重连接table:" + linemsg.tableId + " seatid:" + linemsg.seatId);
                LoginResult = this.sever.LoginRoombyLineOut(this.getUser(_userId), _socket, linemsg.tableId, linemsg.seatId);
                this.lineOutSet({state: 0, userId: _userId});
            } else {
                LoginResult = this.sever.LoginRoom(this.getUser(_userId), _socket);
            }
            //进入房间后，帮分配座位
            // LoginResult
            //发送场景消息给当前用户
            var tableUserList = Array();

            for (var i = 0; i < this.sever.seatMax; i++) {
                //除了自己以外
                //log.info(LoginResult.tableId);
                //log.info(this.sever.tableList);
                if (this.sever.tableList[LoginResult.tableId][i] && this.sever.tableList[LoginResult.tableId][i] != _userId) {
                    var userItem = {};
                    var userid = this.sever.tableList[LoginResult.tableId][i];

                    if (this.userList[userid]) {
                        //先确定在线才能拿到相关信息
                        userItem.userId = this.userList[userid].getUserId();
                        userItem.seatId = this.userList[userid].getSeat();
                        userItem.nickname = this.userList[userid]._nickname;
                        userItem.score = this.userList[userid]._score;
                        userItem.userType = this.userList[userid]._Robot;
                        var url = 0;
                        if (this.userList[userid]._headimgurl) {
                            //url = "bosengame.com/weixin/Login/img.aspx?url=" + urlencode(this.userList[userid]._headimgurl);
                            url = ""
                        }

                        userItem.headimgurl = url;
                        tableUserList.push(userItem);
                    }
                }
            }
            //发送场景消息
            //检查自己下注情况,效准玩家金额
            var self = this;
            gameDao.getFreeCount(_userId, function (ResultCode, Result) {
                //log.info("**" + Result.Id);
                if (!self.userList[_userId]) return;
                Result.Id = _userId
                self.userList[_userId].updateFreeGame(Result);
                log.info("从数据库里获得免费次数" + Result.freeCount);

                var ResultData = {
                    TableId: LoginResult.tableId,
                    seatId: LoginResult.seatId,
                    userList: tableUserList,
                    freeCount: self.userList[_userId].getFreeCount(),
                    score_pool: self.A.getVirtualScorePool()
                };
                _socket.emit("LoginRoomResult", {ResultCode: 1, ResultData: ResultData});

                if (!linemsg.Result) {
                    var tablestring = "table" + LoginResult.tableId;
                    var url = 0;
                    if (self.userList[_userId]._headimgurl) {
                        //url = "bosengame.com/weixin/Login/img.aspx?url=" + urlencode(self.userList[_userId]._headimgurl);
                        url = ""
                    }
                    _socket.broadcast.to(tablestring).emit('playEnter', {
                        ResultCode: 1,
                        ResultData: {
                            userId: _userId,
                            TableId: LoginResult.tableId,
                            seatId: LoginResult.seatId,
                            nickname: self.userList[_userId]._nickname,
                            score: self.userList[_userId]._score,
                            headimgurl: url,
                            userType: self.userList[_userId]._Robot
                        }
                    });
                }

            })

        };

        //登录获取免费次数
        this.LoginfreeCount = function (_userId, _socket) {
            var self = this;
            gameDao.getFreeCount(_userId, function (ResultCode, Result) {
                if (!self.userList[_userId]) return;
                Result.Id = _userId;
                self.userList[_userId].updateFreeGame(Result);
                log.info("从数据库里获得免费次数" + Result.freeCount);
                _socket.emit("LoginfreeCountResult", {ResultCode: 1, freeCount: Result.freeCount});
            })
        };


        //断线保存
        this.lineOutSet = function (_info) {
            if (_info.state == 1) {
                //添加
                this.lineOutList[_info.userId] = {tableId: _info.tableId, seatId: _info.seatId}
                //log.info(this.lineOutList[_info.userId]);
            } else {
                //移除
                this._Csocket.emit("lineOut", {
                    signCode: gameConfig.LoginServeSign,
                    state: 0,
                    gameId: gameConfig.gameId,
                    userId: _info.userId
                });
                delete this.lineOutList[_info.userId];
            }
        };

        //获得断线用户信息
        this.getLineOutMsg = function (_userId) {
            if (this.lineOutList[_userId]) {
                this.lineOutList[_userId].Result = 1;
                return this.lineOutList[_userId];
            } else {
                return {Result: 0};
            }
        };

        //清楚断线用户信息
        this.cleanLineOut = function () {
            //清理登录服务器
            log.info(this.lineOutList)
            for (var Item in this.lineOutList) {
                Item = parseInt(Item)
                var tableid = this.lineOutList[Item].tableId;
                var tablestring = "table" + tableid;
                this._io.sockets.in(tablestring).emit('PlayerOut', {
                    PlayerSeatId: this.lineOutList[Item].seatId,
                    userId: Item
                });
                this.sever.cleanLineOut(tableid, this.lineOutList[Item].seatId);
                this._Csocket.emit("lineOut", {
                    signCode: gameConfig.LoginServeSign,
                    state: 0,
                    gameId: gameConfig.gameId,
                    userId: Item
                })
            }
            this.lineOutList = {};
        };

        this.disconnectAllUser = function () {
            for (var itme in this.userList) {
                this.userList[itme]._socket.disconnect();
            }
            log.info("服务器开启维护，已经全部离线");
        };

        //运行初始化
        this.init();
    };


    if (_gameinfo) {
        return {getInstand: _gameinfo}
    } else {
        log.info("####create game!####");
        _gameinfo = new Game();
        return {getInstand: _gameinfo}
    }

}();

function RandomNumBoth(Min, Max) {
    //生成指定范围内随机整数
    var Range = Max - Min;
    var Rand = Math.random();
    var num = Min + Math.round(Rand * Range); //四舍五入
    return num;
}

function isEmptyObject(obj) {
    //判断是否空字典
    for (var key in obj) {
        return false;
    }
    return true;
}


module.exports = GameInfo;

//监听gm发送来的消息
redis_send_and_listen.client_1.on("message", function (channel, message) {
    log.info("------------------------------server接收到信息了");
    log.info("channel" + channel);
    log.info("message" + message);
    var message = JSON.parse(message);
    if (channel == "EditLabaSet") {
        if (parseInt(message.serverId) == gameConfig.serverId) {
            if (parseInt(message.type) == 1) {    //修改水位
                GameInfo.getInstand.A.nGamblingWaterLevelGold = parseInt(message.swval);
                log.info("修改水位", GameInfo.getInstand.A.nGamblingWaterLevelGold)
            }
            if (parseInt(message.type) == 2) {    //修改难度
                GameInfo.getInstand.A.nGamblingBigWinLevel = message.BigWinlevel.split(',').map(Number);  //大奖幸运等级
                GameInfo.getInstand.A.nGamblingBigWinLuck = message.BigWinluck.split(',').map(Number);    //大奖幸运概率
                log.info("修改难度等级", GameInfo.getInstand.A.nGamblingBigWinLevel);
                log.info("修改难度幸运", GameInfo.getInstand.A.nGamblingBigWinLuck)
            }

        }
    }

});
